<template>
    <div class="content_container" ref="box">
        <div class="left_container statistic">
            <div class="statistic_center">
                <!-- linechart -->
                <div class="left">
                    <div class="block">
                        <el-date-picker v-model="taskDate" type="monthrange" range-separator="至" start-placeholder="开始月份"
                            end-placeholder="结束月份" class="date" @change="changeDate" value-format="yyyy-MM">
                        </el-date-picker>
                        <el-button icon="el-icon-download" circle size="mini" @click="downLoadTask(taskDate)"></el-button>
                    </div>
                    <div id="line_chart" ref="lineChart"></div>
                </div>
                <!-- pieChart/sortChart -->
                <div id="pie_chart" ref="pieChart" class="right"></div>
                <div class="back" v-if="sortChart">
                    <el-select v-model="sortSearch" filterable remote reserve-keyword :remote-method="remoteMethod"
                        :loading="loading" class="input" style="width: 140px;" @change="search">
                        <el-option v-for="item in sortOptions" :key="item.id" :label="item.mobilePhone" :value="item.id">
                        </el-option>
                    </el-select>
                    <el-button icon="el-icon-search" circle size="mini" @click="searchShow"></el-button>
                    <el-button icon="el-icon-refresh-left" circle size="mini" @click="sortChange"></el-button>
                </div>
                <div class="next" v-if="pieChart">
                    <el-button icon="el-icon-download" circle size="mini" @click="downLoadUser(taskDate)"></el-button>
                    <el-button type="primary" icon="el-icon-d-arrow-left" circle size="mini" @click="nextPie('minus')"
                        v-if="pieQueryParams.pageNo > 1"></el-button>
                    <el-button type="primary" icon="el-icon-d-arrow-right" circle size="mini"
                        v-if="pieQueryParams.pageNo < pieMax" @click="nextPie('add')"></el-button>
                </div>
            </div>
            <div class="statistic_bottom">
                <div class="statistic_bottom_btn">
                    <el-select v-model="barQueryParams.sortType" style="margin-right: 10px;" @change="barInit(taskDate)">
                        <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value">
                        </el-option>
                    </el-select>
                    <el-button icon="el-icon-download" circle size="mini" @click="downLoadTools(taskDate)"></el-button>
                    <el-button type="primary" icon="el-icon-d-arrow-left" circle size="mini"
                        v-if="barQueryParams.pageNo > 1" @click="nextBar('minus')"></el-button>
                    <el-button type="primary" icon="el-icon-d-arrow-right" circle size="mini"
                        v-if="barQueryParams.pageNo < barMax" @click="nextBar('add')"></el-button>
                </div>
                <!-- barChart -->
                <div id="barChart" ref="barChart" class="barChart"></div>
            </div>
        </div>
    </div>
</template>
 

<script>
import elementResizeDetectorMaker from 'element-resize-detector'
import {
    taskAmountStatisticRequest,
    downloadTaskAmountStatisticRequest,
    downloadUsageStatisticRequest,
    usageStatisticRequest,
    viewUserDrawStatisticDetailRequest,
    searchDrawUserRequest,
    toolUseStatisticRequest,
    downloadToolUseStatisticRequest
} from '@/api/management'
import store from '@/store';
import { deepClone, throttle } from '@/utils';
import mixins from './mixins';
export default {
    name: 'BaiaoweifanUiUserIndex',
    mixins: [mixins],
    data() {
        return {
            typeOptions: [
                { label: '总数', value: 'total' },
                { label: '成功率', value: 'success' },
                { label: '失败率', value: 'Failure' }
            ],
            loading: false,
            btnList: this.$store.state.login.buttonPermissionList,
            taskDate: [new Date().getFullYear() + '-01', new Date().getFullYear() + '-12'],
            lineChart: null,
            lineChartOption: {},
            pieChart: null,
            pieQueryParams: { pageNo: 1, pageSize: 10 },
            pieMax: null,
            pieChartOption: {},
            sortChart: null,
            sortChartOption: {},
            barChart: null,
            barMax: null,
            barQueryParams: { pageNo: 1, pageSize: 10, sortType: 'total' },
            barChartOption: {},
            sortSearch: '',
            searchflag: true,
            sortOptions: []
        };
    },
    mounted() {
        this.init(this.taskDate)
        this.pieInit(this.taskDate)
        this.barInit(this.taskDate)
        this.chartResize()
    },
    methods: {
        changeDate(value) {
            this.init(value)
            this.pieInit(value)
            this.barInit(value)
        },
        chartResize() {
            let changeSize = elementResizeDetectorMaker()
            let chartDom = document.querySelector('.left')
            changeSize.listenTo(chartDom, () => {
                this.$nextTick(() => {
                    if (this.lineChart) this.lineChart.resize()
                    if (this.pieChart) this.pieChart.resize()
                    if (this.barChart) this.barChart.resize()
                    if (this.sortChart) this.sortChart.resize()
                });
            })
        },
        async init(value) {
            let startMonth = value ? value[0] : null
            let endMonth = value ? value[1] : null
            const { code, data, message } = await taskAmountStatisticRequest({ startMonth, endMonth })
            if (code !== 200) return this.$message.error(message)
            if (this.lineChart) this.lineChart.dispose()
            this.lineChartOption = {
                title: {
                    text: '任务量统计表',
                    left: 'center'
                },
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    data: data.legendData,
                    right: '1%'
                },
                grid: {
                    left: '2%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: data.xaxisData
                },
                yAxis: {
                    type: 'value'
                },
                series: data.series
            }
            this.lineChart = this.$echarts.init(this.$refs.lineChart)
            this.lineChart.setOption(this.lineChartOption)
        },
        nextPie(value) {
            if (value === 'add') {
                this.pieQueryParams.pageNo++
            } else {
                this.pieQueryParams.pageNo--
            }
            this.pieInit()
        },
        nextBar(value) {
            if (value === 'add') {
                this.barQueryParams.pageNo++
            } else {
                this.barQueryParams.pageNo--
            }
            this.barInit(this.taskDate)
        },
        async pieInit(value) {
            this.pieQueryParams.startMonth = value ? value[0] : null
            this.pieQueryParams.endMonth = value ? value[1] : null
            const { data, code, message } = await usageStatisticRequest(this.pieQueryParams)
            if (code !== 200) return this.$message.error(message)
            this.pieMax = data.pageCount
            if (this.pieChart) this.pieChart.dispose()
            this.pieChartOption = {
                title: {
                    text: '用户使用统计表',
                    left: 'center'
                },
                tooltip: {
                    trigger: 'item'
                },
                legend: {
                    orient: 'vertical',
                    left: 'left'
                },
                series: [
                    {
                        type: 'pie',
                        radius: '50%',
                        center: ['62%', '50%'],
                        data: data.seriesData,
                        emphasis: {
                            itemStyle: {
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: 'rgba(0, 0, 0, 0.5)'
                            }
                        }
                    }
                ]
            }
            this.pieChart = this.$echarts.init(this.$refs.pieChart)
            this.pieChart.on('click', this.pieChange)
            this.pieChart.setOption(this.pieChartOption)
        },
        pieChange(params) {
            this.searchflag = true
            this.pieChart.dispose()
            this.pieChart = null
            this.toolSort(params.data)
        },
        async toolSort(params) {
            const id = params.id
            const toolCount = 10
            const { code, data, message } = await viewUserDrawStatisticDetailRequest({ id, toolCount })
            if (code !== 200) return this.$message.error(message)
            if (this.sortChart) this.sortChart.dispose()
            this.sortChartOption = {
                title: {
                    text: params.name,
                    left: 'left'
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        // Use axis to trigger tooltip
                        type: 'shadow' // 'shadow' as default; can also be 'line' or 'shadow'
                    }
                },
                legend: {},
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: {
                    type: 'value'
                },
                yAxis: {
                    type: 'category',
                    data: data.yaxisData
                },
                series: [
                    {
                        name: '成功',
                        type: 'bar',
                        stack: 'total',
                        label: {
                            show: true
                        },
                        emphasis: {
                            focus: 'series'
                        },
                        data: data.successCountList,
                        itemStyle: { color: 'green' }
                    },
                    {
                        name: '失败',
                        type: 'bar',
                        stack: 'total',
                        label: {
                            show: true
                        },
                        emphasis: {
                            focus: 'series'
                        },
                        data: data.failCountList,
                        itemStyle: { color: 'red' }
                    }
                ]
            }
            this.sortChart = this.$echarts.init(this.$refs.pieChart)
            // this.sortChart.on('click', this.sortChange)
            this.sortChart.setOption(this.sortChartOption)
        },
        sortChange(params) {
            this.sortChart.dispose()
            this.sortChart = null
            this.pieInit(this.taskDate)
        },
        async barInit(value) {
            this.barQueryParams.startMonth = value ? value[0] : null
            this.barQueryParams.endMonth = value ? value[1] : null
            if (this.barChart) this.barChart.dispose()
            const { data, code, message } = await toolUseStatisticRequest(this.barQueryParams)
            if (code !== 200) return this.$message.error(message)
            this.barMax = data.pageCount
            this.barChartOption = {
                title: {
                    text: '工具使用统计表',
                    left: 'center'
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        // Use axis to trigger tooltip
                        type: 'shadow' // 'shadow' as default; can also be 'line' or 'shadow'
                    },
                    formatter(params) {
                        let title = `<b>${params[0].name}`
                        if (params.length < 3) {
                            for (let index = 0; index < params.length; index++) {
                                title += `<br>${params[index].marker}${params[index].seriesName} : ${params[index].data}`
                            }
                            return title
                        } else {
                            let total = params[0].data
                            for (let index = 0; index < params.length; index++) {
                                let data = params[index].data
                                let seriesName = params[index].seriesName
                                let marker = params[index].marker
                                if (!index) {
                                    title += `<br>${marker + seriesName} : ${data}`
                                } else {
                                    title += `<br>${marker + seriesName} : ${data} - ${((data / total) * 100).toFixed(1)}%`
                                }
                            }
                            return title
                        }
                    }
                },
                legend: {
                    left: '1%',
                },
                grid: {
                    left: '2%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    data: data.xaxisData,
                    axisLabel: {
                        interval: 0
                    }
                },
                yAxis: {
                    type: 'value',
                },
                series: [
                    {
                        name: '总数',
                        type: 'bar',
                        // stack: 'total',
                        label: {
                            show: true
                        },
                        emphasis: {
                            focus: 'series'
                        },
                        data: data.totalCountList,
                        itemStyle: { color: 'blue' },
                    },
                    {
                        name: '成功',
                        type: 'bar',
                        stack: 'total',
                        label: {
                            show: true
                        },
                        emphasis: {
                            focus: 'series'
                        },
                        data: data.successCountList,
                        itemStyle: { color: 'green' }
                    },
                    {
                        name: '失败',
                        type: 'bar',
                        stack: 'total',
                        label: {
                            show: true
                        },
                        emphasis: {
                            focus: 'series'
                        },
                        data: data.failCountList,
                        itemStyle: { color: 'red' }
                    }
                ]
            }
            this.barChart = this.$echarts.init(this.$refs.barChart)
            this.barChart.setOption(this.barChartOption)
        },
        searchShow() {
            const item = document.querySelector('.input')
            if (this.searchflag) {
                this.sortSearch = ''
                item.style.transform = 'translateX(0)'
                item.style.opacity = 1
                item.style.transition = 'all 0.5s'
                item.style.zIndex = 999
                this.searchflag = !this.searchflag
            } else {
                this.searchClose()
            }
        },
        searchClose() {
            this.searchflag = !this.searchflag
            const item = document.querySelector('.input')
            item.style.transform = 'translateX(100px)'
            item.style.opacity = 0
            item.style.transition = 'all 0.5s'
            item.style.zIndex = -999
        },
        search(value) {
            const params = { id: value }
            this.toolSort(params)
            this.searchClose()
        },
        async downLoadTask(value) {
            let startMonth = value ? value[0] : null
            let endMonth = value ? value[1] : null
            const res = await downloadTaskAmountStatisticRequest({ startMonth, endMonth })
            let name = startMonth && endMonth ? startMonth + '至' + endMonth + '任务量统计表.xls' : '任务量统计表.xls'
            this.$dropDown(res, name)
        },
        async downLoadUser(value) {
            let startMonth = value ? value[0] : null
            let endMonth = value ? value[1] : null
            const res = await downloadUsageStatisticRequest({ startMonth, endMonth })
            this.$dropDown(res, '用户使用统计表.xls')
        },
        async downLoadTools(value) {
            let startMonth = value ? value[0] : null
            let endMonth = value ? value[1] : null
            const res = await downloadToolUseStatisticRequest({ startMonth, endMonth, sortType: this.barQueryParams.sortType })
            this.$dropDown(res, '工具使用统计表.xls')
        },
        async remoteMethod(query) {
            if (query !== '') {
                this.loading = true;
                const res = await searchDrawUserRequest({ keyword: query })
                if (res.code !== 200) return this.$message.error(res.message)
                this.loading = false;
                this.sortOptions = res.data
            } else {
                this.sortOptions = [];
            }
        },
    },
    beforeDestroy() {
        if (this.lineChart) this.lineChart.dispose()
        if (this.pieChart) this.pieChart.dispose()
        if (this.sortChart) this.sortChart.dispose()
        if (this.barChart) this.barChart.dispose()
        this.lineChart = null
        this.pieChart = null
        this.sortChart = null
        this.barChart = null
    },

};
</script>

<style lang="scss" scoped>
.statistic_center {
    position: relative;
    display: flex;
    justify-content: space-between;
    margin-bottom: 25px;

    ::v-deep .el-input__inner {
        height: 30px;
        line-height: 30px;
        border-radius: 6px;

        .el-range-separator {
            line-height: 24px;
        }

        .el-range__icon {
            line-height: 24px;
        }

        .el-range__close-icon {
            line-height: 24px;
        }
    }

    .left {
        width: 60%;
        height: 400px;
        display: flex;
        padding: 5px;
        flex-direction: column;
        border-radius: 6px;
        box-shadow: 2px 2px 5px 3px #ccc;



        #line_chart {
            flex: 1;
        }
    }

    .block {
        position: absolute;
        z-index: 999;

        .date {
            width: 210px;
            margin: 0 25px;
        }

    }

    .right {
        width: 38.5%;
        height: 400px;
        padding: 5px;
        border-radius: 6px;
        box-shadow: 2px 2px 5px 3px #ccc;
    }

    .next {
        position: absolute;
        right: 10px;
        top: 10px;
    }

    .back {
        display: flex;
        position: absolute;
        top: 12px;
        right: 12px;

        .input {
            // display: none;
            transform: translateX(100px);
            opacity: 0;
            z-index: -999;
        }
    }
}

.statistic_bottom {
    height: 550px;
    display: flex;
    padding: 5px;
    flex-direction: column;
    border-radius: 6px;
    box-shadow: 2px 2px 5px 3px #ccc;
    position: relative;

    .statistic_bottom_btn {
        position: absolute;
        right: 10px;
        top: 10px;
        z-index: 999;

        ::v-deep .el-input__inner {
            width: 90px;
            border-radius: 6px;
            height: 32px;
            line-height: 32px;
        }

        ::v-deep .el-input__icon {
            line-height: 32px;
        }
    }

    .barChart {
        height: 100%;
    }
}
</style>